import React from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Divider } from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DictCode from '../../components/DictCode';
import BatchUpload from '../../components/BatchUpload/Index';
import StepItem from '../../components/BatchUpload/StepItem';
import FileUpload from '../../components/BatchUpload/Upload';
import Finish from '../../components/BatchUpload/Finish';
import { urlParse } from '@/utils/utils';

const formItemLayout = {
  labelCol: {
    span: 10,
  },
  wrapperCol: {
    span: 14,
  },
};
@connect(({ batchadjust, publicdata, loading }) => ({
  uploading: loading.effects['batchadjust/uploadFileWithProgress'],
  batchQuery: batchadjust.batchQuery,
  fileId: publicdata.downloadFile.fileId,
  fileName: publicdata.downloadFile.fileName,
  currentStep: batchadjust.currentStep,
  progressPercent: batchadjust.progressPercent,
  resultInfo: batchadjust.resultInfo,
  showProgress: batchadjust.showProgress,
}))
@Form.create({
  mapPropsToFields(props) {
    const { batchQuery } = props;
    return {
      batchAdjType: Form.createFormField({ value: batchQuery.batchAdjType }),
      decWageFlag: Form.createFormField({ value: batchQuery.decWageFlag }),
      lsPkgFlag: Form.createFormField({ value: batchQuery.lsPkgFlag }),
    };
  },
})
class Batch extends React.PureComponent {
  componentDidMount() {
    const { dispatch, location } = this.props;
    const { batchAdjType } = urlParse(location.search);
    dispatch({
      type: 'batchadjust/updateQuery',
      payload: {
        batchAdjType,
      },
    });
    this.clearModel();
  }

  componentWillUnmount() {
    this.clearModel();
  }

  // 重置model
  clearModel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'batchadjust/updateModelData',
      payload: {
        currentStep: 0,
        progressPercent: 0,
        showProgress: false,
        batchQuery: {
          // 批量上传数据
          decWageFlag: '1',
          lsPkgFlag: '1',
        },
      },
    });
  };

  // 设置当前位置
  setCurrentstep = currentStep => {
    const { dispatch } = this.props;
    dispatch({
      type: 'batchadjust/updateModelData',
      payload: { currentStep },
    });
    if (!currentStep) {
      dispatch({
        type: 'batchadjust/updateModelData',
        payload: {
          currentStep: 0,
          progressPercent: 0,
          showProgress: false,
        },
      });
    }
  };

  // 下一步
  onNext = () => {
    const {
      dispatch,
      form: { validateFields },
      currentStep,
    } = this.props;
    validateFields((err, values) => {
      if (!err) {
        dispatch({
          type: 'batchadjust/getDownloadInfo',
          payload: {
            ...values,
            batchAdjType: '2', // 批量调整类型
          },
        });
      }
    });
    this.setCurrentstep(currentStep + 1);
  };

  // 上传文件：需要携带参数即传：batchQuery
  uploadFile = formData => {
    const { batchQuery, dispatch, location } = this.props;
    const { batchAdjType } = urlParse(location.search);
    const uploadQuery = {
      decWageFlag: batchQuery.decWageFlag,
      lsPkgFlag: batchQuery.lsPkgFlag,
    };
    // 需要携带参数即传：batchQuery，不需要传参可省略
    Object.entries(uploadQuery).forEach(([key, value]) => {
      formData.append(key, value);
    });
    dispatch({
      type: 'batchadjust/uploadFileWithProgress',
      payload: {
        params: formData,
        batchAdjType,
      },
    });
  };

  // 获取单选框的值
  getValue = (e, name) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'batchadjust/accuUpdateModelData',
      payload: {
        state: e.target.value,
        name,
      },
    });
  };

  render() {
    const {
      form,
      fileId,
      fileName,
      uploading,
      batchQuery,
      currentStep,
      showProgress,
      progressPercent,
      resultInfo,
    } = this.props;
    const { getFieldDecorator } = form;
    return (
      <PageHeaderWrapper>
        <BatchUpload currentStep={currentStep}>
          <StepItem title="修改公积金申报信息">
            <Form layout="horizontal" style={{ margin: '40px auto 0', maxWidth: 500 }}>
              <Form.Item {...formItemLayout} label="变更申报工资">
                {getFieldDecorator('decWageFlag')(
                  <DictCode
                    inputType="3"
                    dictType="YES_NO_FLAG"
                    onChange={e => this.getValue(e, 'decWageFlag')}
                  />
                )}
              </Form.Item>
              <Form.Item {...formItemLayout} label="变更公积金组合">
                {getFieldDecorator('lsPkgFlag')(
                  <DictCode
                    inputType="3"
                    dictType="YES_NO_FLAG"
                    onChange={e => this.getValue(e, 'lsPkgFlag')}
                  />
                )}
              </Form.Item>
            </Form>
            <div style={{ marginTop: 100, textAlign: 'center' }}>
              <Button onClick={() => router.goBack()} style={{ marginRight: 8 }}>
                返回
              </Button>
              <Button
                type="primary"
                onClick={this.onNext}
                disabled={!!(batchQuery.lsPkgFlag === '2' && batchQuery.decWageFlag === '2')}
              >
                下一步
              </Button>
            </div>
            <Divider dashed style={{ marginTop: 100 }} />
            <p style={{ margin: '0 auto', width: '90%', fontSize: 14 }}>
              说明
              <br />
              1、如需变更申报工资，每人的具体申报工资在下一步中根据模板填写；
              <br />
              2、变更公积金组合可以修改缴纳比例、缴纳账户，在下一步中根据模板填写。
            </p>
          </StepItem>
          <FileUpload
            title="上传文件"
            currentStep={currentStep}
            setCurrentstep={this.setCurrentstep}
            downloadTempInfo={{
              // 下载模板信息
              params: { fileId, fileName },
              url: '/csApi/batchTask/downloadFile',
            }}
            uploadFile={this.uploadFile}
            uploading={uploading}
            // 展示进度条需要的数据
            progressPercent={progressPercent || 0}
            progressTitle="批量调整任务"
            progressVisible={showProgress}
          />
          <Finish title="完成" resultInfo={resultInfo} setCurrentstep={this.setCurrentstep} />
        </BatchUpload>
      </PageHeaderWrapper>
    );
  }
}

export default Batch;
